import { createApp } from 'vue';
import AppModal from '../../components/common/app-modal';
import { modalController } from '@ionic/core';
import { IParam } from 'ibz-core';
import { LogUtil, Util } from 'ibz-core';
import { Subject } from 'rxjs';
import { IPSAppView } from '@ibiz/dynamic-model-api';
import { IonicVue } from '@ionic/vue';
import { ComponentRegister } from '../../register';
import { translate } from '../../locale';
/**
 * 模态框工具
 *
 * @export
 * @class AppModalService
 */
export class AppModalService {
  /**
   * 实例对象
   *
   * @private
   * @static
   * @memberof AppModalService
   */
  private static modal = new AppModalService();

  /**
   * Creates an instance of AppModalService.
   *
   * @memberof AppModalService
   */
  constructor() {
    if (AppModalService.modal) {
      return AppModalService.modal;
    }
  }

  /**
   * 获取单例对象
   *
   * @static
   * @returns {AppModalService}
   * @memberof AppModalService
   */
  public static getInstance(): AppModalService {
    if (!AppModalService.modal) {
      AppModalService.modal = new AppModalService();
    }
    return AppModalService.modal;
  }

  /**
   * 创建 Vue 实例对象
   *
   * @private
   * @param {{ viewComponent?: any,viewPath:string, viewModel: IParam, customClass?: string, customStyle?: IParam, }} view
   * @param {*} [navContext={}]
   * @param {*} [navParam={}]
   * @param {Array<any>} [navDatas=[]]
   * @param {*} viewCtx
   * @param {string} uuid
   * @return {*}  {Promise<any>}
   * @memberof AppModalService
   */
  private async createVueExample(
    view: {
      viewComponent?: any;
      viewPath?: string;
      viewModel?: IParam;
      customClass?: string;
      customStyle?: IParam;
    },
    navContext: any = {},
    navParam: any = {},
    navDatas: Array<any> = [],
    otherParam: any,
    uuid: string,
    subject: Subject<any>,
  ): Promise<any> {
    const model = await this.createModal(null, uuid);
    const el = document.getElementById(`${uuid}`)?.getElementsByClassName('ion-page')?.[0];
    const props = { view, navContext, navParam, navDatas, model, otherParam, subject, viewShowMode: 'MODEL' };
    const vm = createApp(AppModal, props)
      .use(ComponentRegister)
      .use(App.getUserRegister())
      .use(IonicVue)
      .use(App.getI18n());
    // 添加全局翻译api
    vm.config.globalProperties.$tl = function (key: string, value?: string) {
      return translate(key, this, value);
    };
    vm.config.warnHandler = (msg: any, vm: any, trace: any) => {
      if (
        !msg.startsWith('Extraneous non-emits') &&
        !msg.startsWith('Extraneous non-props') &&
        !msg.startsWith('injection')
      ) {
        console.warn(msg, trace);
      }
    };
    const subscribe = subject.subscribe(() => {
      vm.unmount();
      subscribe.unsubscribe();
    });
    if (el) {
      vm.mount(el);
    }
  }

  /**
   * 打开 ionic 模式模态框
   *
   * @private
   * @param {Element} ele
   * @returns {Promise<any>}
   * @memberof AppModalService
   */
  private async createModal(ele: any, uuid: string): Promise<any> {
    const modal = await modalController.create({
      component: ele,
      id: uuid,
    });
    await modal.present();
    return modal;
  }

  /**
   * 打开模态视图
   *
   * @param {{ viewComponent?: any, viewPath: string, viewModel: IParam, customClass?: string, customStyle?: IParam }} view
   * @param {*} [navContext={}]
   * @param {*} [navParam={}]
   * @param {Array<any>} [navDatas=[]]
   * @param {*} [otherParam={}]
   * @return {*}  {Subject<any>}
   * @memberof AppModalService
   */
  public openModal(
    view: {
      viewComponent?: string;
      viewPath?: string;
      viewModel?: IParam;
      customClass?: string;
      customStyle?: IParam;
    },
    navContext: any = {},
    navParam: any = {},
    navDatas: Array<any> = [],
    otherParam: any = {},
  ): Subject<any> {
    const subject: Subject<{ ret: boolean; datas?: IParam[] }> = new Subject<{ ret: boolean; datas?: IParam[] }>();
    try {
      const _navContext: any = {};
      Object.assign(_navContext, navContext);
      if (!view.viewComponent) {
        this.fillView(view);
      }
      const uuid = Util.createUUID();
      this.createVueExample(view, _navContext, navParam, navDatas, otherParam, uuid, subject);
      return subject;
    } catch (error) {
      LogUtil.warn(error);
      return subject;
    }
  }

  /**
   *  初始化视图名称
   *
   * @memberof AppModalService
   */
  public fillView(view: any) {
    if (Util.isEmpty(view.viewModel)) {
      return;
    } else {
      view.viewComponent = App.getComponentService().getViewTypeComponent(
        (view.viewModel as IPSAppView).viewType,
        (view.viewModel as IPSAppView).viewStyle,
        (view.viewModel as IPSAppView)?.getPSSysPFPlugin()?.pluginCode,
      );
      view.viewPath = (view.viewModel as IPSAppView).modelPath;
    }
  }
}
